from rest_framework import serializers

from drfstudy.models import Student, Classes


# 序列化器
class StudentSerializer(serializers.ModelSerializer):
    class_name = serializers.CharField(source='classes.name', read_only=True)

    def validate(self, attrs):
        if attrs.get('age') < 18:
            raise serializers.ValidationError("未成年")
        return attrs

    class Meta:
        # 将Student模型转化为序列化器
        model = Student
        # 展示指定字段
        # 展示所有字段
        # fields = '__all__'
        exclude = ['create_time', 'update_time', 'is_delete']
        # 数据校验
        extra_kwargs = {
            'age': {'min_value': 0, 'max_value': 100},
            'classes': {'write_only': True}
        }

    # validated_data ->>需要创建的数据以字典的形式
    # def create(self, validated_data):
    #     return Student.objects.create(**validated_data)
    #
    # def update(self, instance, validated_data):
    #     # validated_data->>修改数据
    #     # instance->>原本的数据
    #     instance.name = validated_data.get('name', instance.name)
    #     instance.age = validated_data.get('age', instance.age)
    #     instance.sex = validated_data.get('sex', instance.sex)
    #     instance.save()
    #     return instance


class StudentClassSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['name', 'sex', 'age']


class ClassesSerializer(serializers.ModelSerializer):
    student_set = StudentClassSerializer(many=True, read_only=True)

    class Meta:
        model = Classes
        fields = ['name', 'slogan', 'student_set']
